<?php

namespace App\Admin\Controllers\Actions\Post;

use App\Extensions\Actions\RowAction;
use App\PatentApply;
use App\PatentAssess;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PatentAssessPost extends RowAction
{
    public $name = '评估意见';

    public function handle(PatentApply $apply, Request $request)
    {
        $user = Admin::user();
        DB::beginTransaction();
        try {
            /** @var PatentAssess $model */
            $model = $apply->assesses()->create([
                'score'     => $request->get('score'),
                'remark'    => $request->get('remark'),
                'state'     => 1,
                'expert_id' => $user['id'],
            ]);
            if ($file = $request->file('file')) {
                $model->storeFile($file, 'path');
            }
            $apply->syncScore();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->swal()->error('操作失败！')->refresh();
        }

        return $this->response()->success('操作完成！')->refresh();
    }

    public function form()
    {
        $mimes = 'png,jpg,jpeg,pdf';
        $this->text('score', '评分')
            ->rules('required|numeric', ['required' => '评分不能为空', 'numeric' => '请输入有效数字']);
        $this->file('file', '评估报告')
            ->rules('required|mimes:' . $mimes, ['required' => '请上传评估报告', 'mimes' => '评估报告类型错误'])
            ->help('类型：' . $mimes);
        $this->textarea('remark', '评估意见')->required()->placeholder('100-200字左右');
    }

    public function __toString()
    {
        if (config('settings.module.expert_module')) {
            return $this->render();
        }
        return '';
    }
}
